package meijuli.com.join51.business.ui.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.widget.EditText
import me.foji.anko.afterTextChanged
import me.foji.anko.clear
import meijuli.com.join51.business.R

/**
 * 带清除功能的edittext
 *
 * @author Jack 2018-01-18 19:21
 */
class ClearEditText(context: Context, attributeSet: AttributeSet) : EditText(context, attributeSet) {

    init {
        val drawable = context.resources.getDrawable(R.mipmap.icon_clear)
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)

        if(text.isNotEmpty() && hasFocus()) {
            setCompoundDrawables(null, null, drawable, null)
        } else {
            setCompoundDrawables(null, null, null, null)
        }

        afterTextChanged {
            if(text.isNotEmpty() && hasFocus()) {
                setCompoundDrawables(null, null, drawable, null)
            } else {
                setCompoundDrawables(null, null, null, null)
            }
        }

        setOnFocusChangeListener { _, hasFocus ->
            if(text.isNotEmpty() && hasFocus) {
                setCompoundDrawables(null, null, drawable, null)
            } else {
                setCompoundDrawables(null, null, null, null)
            }
        }

        setOnTouchListener { _, event ->
            when {
                event.action == MotionEvent.ACTION_DOWN -> {
                    if(event.rawX > right - drawable.minimumWidth - paddingRight) {
                        clear()
                        return@setOnTouchListener true
                    }
                }
            }
            return@setOnTouchListener super.onTouchEvent(event)
        }
    }

}